<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          v-model="queryParams.hospitalName"
          placeholder="请输入医院名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院等级" prop="hospitalLevel">
        <el-select v-model="queryParams.hospitalLevel" placeholder="请选择医院等级" clearable>
          <el-option
            v-for="dict in dict.type.hospital_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hospitals:hospitals:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hospitals:hospitals:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hospitals:hospitals:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hospitals:hospitals:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hospitalsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 展开详情列（医院简介） -->
      <el-table-column type="expand" label="医院简介" align="center" prop="hospitalId">
        <template #default="scope">
          <el-card shadow="hover"  style="padding: 12px; border-radius: 4px;">
          <div v-html="scope.row.description" />  <!-- 支持简单富文本（若有需求） -->
          </el-card>
        </template>
      </el-table-column>

      <!-- 医院名称 -->
      <el-table-column label="医院名称" align="center" prop="hospitalName" show-overflow-tooltip/>

      <el-table-column label="医院等级" align="center" prop="hospitalLevel" >
        <template #default="scope">
          <dict-tag :options="dict.type.hospital_level" :value="scope.row.hospitalLevel"
                    :max-width="100" show-overflow-tooltip
          />
        </template>
      </el-table-column>

      <!-- 地址 -->
      <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip/>

      <!-- 联系电话 -->
      <el-table-column label="联系电话" align="center" prop="phone" width="140" show-overflow-tooltip/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hospitals:hospitals:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hospitals:hospitals:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医院信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="form.hospitalName" placeholder="请输入医院名称" />
        </el-form-item>
        <el-form-item label="医院等级" prop="hospitalLevel">
          <el-select v-model="form.hospitalLevel" placeholder="请选择医院等级">
            <el-option
              v-for="dict in dict.type.hospital_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="医院简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHospitals, getHospitals, delHospitals, addHospitals, updateHospitals } from "@/api/hospitals/hospitals"

export default {
  name: "Hospitals",
  dicts: ['hospital_level'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      hospitalsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalName: null,
        hospitalLevel: null,
        deleted: null
      },
      form: {},
      rules: {
        hospitalName: [
          { required: true, message: "医院名称不能为空", trigger: "blur" }
        ],
        hospitalLevel: [
          { required: true, message: "医院等级不能为空", trigger: "change" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询医院信息列表 */
    getList() {
      this.loading = true
      listHospitals(this.queryParams).then(response => {
        this.hospitalsList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(error => {
        console.error('获取医院列表失败', error)
        this.$modal.msgError('获取医院列表失败')
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        hospitalId: null,
        hospitalName: null,
        hospitalLevel: null,
        address: null,
        phone: null,
        description: null,
        createTime: null,
        updateTime: null,
        deleted: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hospitalId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加医院信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 确保只处理单个医院ID
      const hospitalId = row?.hospitalId || (this.ids.length > 0 ? this.ids[0] : null)

      // 校验ID是否存在
      if (!hospitalId) {
        this.$modal.msgWarning('请选择要修改的医院')
        return
      }

      this.reset() // 重置表单

      // 根据ID获取医院详情
      getHospitals(hospitalId).then(response => {
        // 直接赋值确保数据正确回显
        if (response.data) {
          this.form = response.data
          this.open = true
          this.title = "修改医院信息"
        } else {
          this.$modal.msgError('获取医院信息失败，数据不存在')
        }
      }).catch(error => {
        console.error('获取医院详情失败', error)
        this.$modal.msgError('获取医院详情失败，请稍后重试')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 根据是否存在ID判断是新增还是修改
          if (this.form.hospitalId) {
            updateHospitals(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('修改医院失败', error)
              this.$modal.msgError('修改医院失败，请稍后重试')
            })
          } else {
            addHospitals(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('新增医院失败', error)
              this.$modal.msgError('新增医院失败，请稍后重试')
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const hospitalIds = row?.hospitalId ? [row.hospitalId] : this.ids

      if (hospitalIds.length === 0) {
        this.$modal.msgWarning('请选择要删除的医院')
        return
      }

      this.$modal.confirm(`是否确认删除医院信息编号为"${hospitalIds.join(',')}"的数据项？`).then(() => {
        delHospitals(hospitalIds).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(error => {
          console.error('删除医院失败', error)
          this.$modal.msgError('删除医院失败，请稍后重试')
        })
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hospitals/hospitals/export', {
        ...this.queryParams
      }, `hospitals_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
